package com.seecen.HJM.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.HJM.constant.JwtClaimsConstant;
import com.seecen.HJM.constant.MessageConstant;
import com.seecen.HJM.enumeration.LikeStatusEnum;
import com.seecen.HJM.mapper.PlaylistMapper;
import com.seecen.HJM.mapper.SongMapper;
import com.seecen.HJM.mapper.UserFavoriteMapper;
import com.seecen.HJM.model.dto.PlaylistDTO;
import com.seecen.HJM.model.dto.SongDto;
import com.seecen.HJM.model.entity.UserFavorite;
import com.seecen.HJM.model.vo.PlayListVo;
import com.seecen.HJM.model.vo.SongVo;
import com.seecen.HJM.result.DataVo;
import com.seecen.HJM.result.PageResult;
import com.seecen.HJM.service.UserFavoriteService;
import com.seecen.HJM.util.ThreadLocalUtil;
import com.seecen.HJM.util.TypeConversionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author TOYA
 * @description 针对表【tb_user_favorite】的数据库操作Service实现
 * @createDate 2025-09-26 22:52:07
 *
 */
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite>
        implements UserFavoriteService {

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;
    @Autowired
    private SongMapper songMapper;
    @Autowired
    private PlaylistMapper playlistMapper;


    //获取用户收藏的歌曲列表
    //@param songDTO 歌曲查询条件
    //@return 用户收藏的歌曲列表
    @Override
    public DataVo<PageResult<SongVo>> getUserFavoriteSongs(SongDto songDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        // 获取用户收藏的歌曲 ID 列表
        List<Long> favoriteSongIds = userFavoriteMapper.getUserFavoriteSongIds(userId);
        if (favoriteSongIds.isEmpty()) {
            return DataVo.success(new PageResult<>(0L, Collections.emptyList()));
        }

        // 分页查询收藏的歌曲，支持模糊查询
        Page<SongVo> page = new Page<>(songDTO.getPageNum(), songDTO.getPageSize());
        IPage<SongVo> songPage = songMapper.getSongsByIds(
                page,
                favoriteSongIds,
                songDTO.getSongName(),
                songDTO.getArtistName(),
                songDTO.getAlbum()
        );

        // 遍历结果，设置 likeStatus
        List<SongVo> songVOList = songPage.getRecords().stream()
                .peek(songVO -> songVO.setLikeStatus(LikeStatusEnum.LIKE.getId())) // 设置为已收藏
                .toList();

        return DataVo.success(new PageResult<>(songPage.getTotal(), songVOList));
    }


    /*
        收藏歌曲
        @param songId 歌曲 ID
         @return 成功或失败
     */
    @Override
    public DataVo collectSong(Long songId) {
        // 1. 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        //查询是否已经收藏了这个歌曲
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("type", 0).eq("song_id", songId);
        //已经收藏
        if (userFavoriteMapper.selectCount(queryWrapper) > 0) {
            return DataVo.error(MessageConstant.ADD + MessageConstant.FAILED);
        }

        //未收藏
        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(userId);
        userFavorite.setType(0);
        userFavorite.setSongId(songId);
        userFavorite.setCreateTime(LocalDateTime.now());
        userFavoriteMapper.insert(userFavorite);

        return DataVo.success(MessageConstant.ADD + MessageConstant.SUCCESS);
    }


    /**
     * 取消收藏歌曲
     *
     * @param songId 歌曲 ID
     * @return 成功或失败
     */
    @Override
    public DataVo cancelCollectSong(Long songId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("type", 0).eq("song_id", songId);
        if (userFavoriteMapper.delete(queryWrapper) == 0) {
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }
        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }


    /**
     * 获取用户收藏的歌单列表
     *
     * @param playlistDTO 歌单查询条件
     * @return 用户收藏的歌单列表
     */
    @Override
    public DataVo<PageResult<PlayListVo>> getUserFavoritePlaylists(PlaylistDTO playlistDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        // 获取用户收藏的歌单 ID 列表
        List<Long> favoritePlaylistIds = userFavoriteMapper.getUserFavoritePlaylistIds(userId);
        if (favoritePlaylistIds.isEmpty()) {
            return DataVo.success(new PageResult<>(0L, Collections.emptyList()));
        }

        // 分页查询收藏的歌单，支持模糊查询
        Page<PlayListVo> page = new Page<>(playlistDTO.getPageNum(), playlistDTO.getPageSize());
        IPage<PlayListVo> playlistPage = playlistMapper.getPlaylistsByIds(
                userId,
                page,
                favoritePlaylistIds,
                playlistDTO.getTitle(),
                playlistDTO.getStyle()
        );

        return DataVo.success(new PageResult<>(playlistPage.getTotal(), playlistPage.getRecords()));
    }


    /**
     * 收藏歌单
     *
     * @param playlistId 歌单 ID
     * @return 成功或失败
     */
    @Override
    public DataVo collectPlaylist(Long playlistId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("type", 1).eq("playlist_id", playlistId);
        if (userFavoriteMapper.selectCount(queryWrapper) > 0) {
            return DataVo.error(MessageConstant.ADD + MessageConstant.FAILED);
        }

        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(userId);
        userFavorite.setType(1);
        userFavorite.setPlaylistId(playlistId);
        userFavorite.setCreateTime(LocalDateTime.now());
        userFavoriteMapper.insert(userFavorite);

        return DataVo.success(MessageConstant.ADD + MessageConstant.SUCCESS);
    }


    /**
     * 取消收藏歌单
     *
     * @param playlistId 歌单 ID
     * @return 成功或失败
     */
    @Override
    public DataVo cancelCollectPlaylist(Long playlistId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object userIdObj = map.get(JwtClaimsConstant.USER_ID);
        Long userId = TypeConversionUtil.toLong(userIdObj);

        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("type", 1).eq("playlist_id", playlistId);
        if (userFavoriteMapper.delete(queryWrapper) == 0) {
            return DataVo.error(MessageConstant.DELETE + MessageConstant.FAILED);
        }

        return DataVo.success(MessageConstant.DELETE + MessageConstant.SUCCESS);
    }
}




